const router = require('koa-router')()
const mongoose = require('mongoose')
const upload = require('../upload')
const statsfn = require('../lib/statsfn')

router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.post('/', upload.single('imgfile'), async ctx => {
  //const {username, password} = ctx.request.body
  
  
  if(ctx.session.user===undefined){
    ctx.redirect(`../login`)
  }else{
    const {title, description} = ctx.req.body
    const {originalname, mimetype, filename: diskfilename} = ctx.req.file
    const doc = await Image.create({
      title, author:ctx.session.user.username,description, originalname, mimetype, diskfilename
    })
    //ctx.session.user = {nickname: 'wobushi汤姆', username: 'tom'}
   
    ctx.redirect(`/images/show/${doc._id}`)
  }
   
  
  
  
})

router.get('/show/:id', async ctx => {
  //ctx.session.user = 'abc'
  //const {username, password} = ctx.request.body
  //ctx.session.user = {nickname: '汤姆', username: 'tom'}
  const doc = await Image.findByIdAndUpdate(
    ctx.params.id,
    {$inc: {visit: 1}},
    {new: true}
  )
  const imguser = await Image.find({"_id":ctx.params.id})
  ctx.session.imginfo = {nickname: imguser[0].author}
  


  const comments  = await Comment.find({})
        .sort({createdAt:-1})
        .limit(3)
  const nearimage = await Image.find({_id:[comments[0].image,comments[1].image,comments[2].image]})
  console.log("author:"+imguser[0].author)
  console.log("author:"+ ctx.session.imginfo.nickname)
  //ctx.session.user = {nickname: '汤姆', username: 'tom'}
  doc.stats = await statsfn()
  doc.comments = await Comment.find({image: ctx.params.id})
    .sort({createdAt: -1})
  doc.imginfo=ctx.session.imginfo
  doc.nearimage=nearimage
  await ctx.render('show', doc)
})

router.post('/likes/:id', async ctx => {
  ctx.body = await Image.findByIdAndUpdate(
    ctx.params.id,
    {$inc: {likes: 1}},
    {new: true}
  )
})

module.exports = router